#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include<cstring>

using namespace std;

void SetNoBlock(int fd)
{
    int fl = fcntl(fd,F_GETFL);
    if(fl < 0)
    {
        perror("fcntl");
        exit(1);
    }
    fcntl(fd,F_SETFL,fl | O_NONBLOCK);
}

int main()
{
    SetNoBlock(0);
    char buffer[1024];
    while(true)
    {
        cout << "Please Enter# ";
        fflush(stdout); 

        ssize_t n = read(0,buffer,sizeof(buffer)-1);
        if(n > 0)
        {
            // 把读上来的数据当做字符串
            buffer[n] = 0;
            cout << "读上来的数据:" << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "读取结束" << endl;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "还没有数据，重新尝试" << endl;
                sleep(1);
            }
            else
            {
 
                cout << "读取失败 n = "  << n << endl;
                cout << "错误码: " << errno << " " << "错误描述: " << strerror(errno) << endl;
            
            }
        }
    }
    return 0;
}